<!-- NotificationView.vue -->
<template>
  <div class="notification-container">
    <div class="notification-header">
      <h2>我的通知</h2>
      <div class="header-actions">
    
      </div>
    </div>
    
    <div class="notification-list" v-loading="loading">
      <template v-if="notificationList.length > 0">
        <div v-for="notification in notificationList" 
             :key="notification.notificationId" 
             class="notification-item"
             :class="{'unread': !notification.read}">
          <div class="notification-content">
            <div class="notification-title">
              <el-icon><Bell /></el-icon>
              <span>{{ notification.title }}</span>
            </div>
            <div class="notification-time">
              {{ formatDate(notification.createTime) }}
            </div>
            <div class="notification-text" v-html="formatContent(notification.content)"></div>
            <div class="notification-actions">
              <el-button 
                v-if="!notification.read"
                type="primary" 
                link 
                @click="markAsRead(notification.notificationId)"
                class="action-button"
              >
                确认
              </el-button>
              <el-button 
                type="danger" 
                link 
                v-if="notification.status === 1"
                @click="confirmDelete(notification.notificationId)"
                class="action-button"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </template>
      <el-empty v-else description="暂无通知" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { Bell } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNotificationList, readNotification, deleteNotification } from '@/api/user'
import eventBus from '@/utils/eventBus'

/**
 * 通知视图组件
 * 功能：展示和管理用户的通知消息，包括：
 * 1. 显示通知列表
 * 2. 标记通知为已读
 * 3. 删除通知
 * 4. 格式化通知时间显示
 */

export default {
  name: 'NotificationView',
  
  components: {
    Bell
  },

  setup() {
    const loading = ref(false)                // 加载状态
    const notificationList = ref([])          // 通知列表数据

    /**
     * 格式化日期显示
     * @param {string} dateStr - ISO格式的日期字符串
     * @returns {string} 格式化后的日期显示
     */
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      
      const now = new Date()
      const date = new Date(dateStr)
      const diff = Math.floor((now - date) / 1000) // 时间差（秒）
      
      // 如果时间差小于1分钟，显示"刚刚"
      if (diff < 60) {
        return '刚刚'
      }
      // 如果时间差小于1小时，显示"x分钟前"
      else if (diff < 3600) {
        return Math.floor(diff / 60) + '分钟前'
      }
      // 如果时间差小于24小时，显示"x小时前"
      else if (diff < 86400) {
        return Math.floor(diff / 3600) + '小时前'
      }
      // 如果时间差小于30天，显示"x天前"
      else if (diff < 2592000) {
        return Math.floor(diff / 86400) + '天前'
      }
      // 如果时间差大于30天，显示具体日期和时间
      else {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hour = String(date.getHours()).padStart(2, '0')
        const minute = String(date.getMinutes()).padStart(2, '0')
        return `${year}-${month}-${day} ${hour}:${minute}`
      }
    }

    /**
     * 格式化通知内容，将换行符转换为HTML标签
     * @param {string} content - 原始通知内容
     * @returns {string} 格式化后的HTML内容
     */
    const formatContent = (content) => {
      if (!content) return ''
      return content.replace(/\n/g, '<br>')
    }

    /**
     * 获取通知列表
     * 从服务器获取用户的通知列表并更新状态
     */
    const fetchNotificationList = async () => {
      loading.value = true
      try {
        const response = await getNotificationList()
        if (response.code === 200) {
          notificationList.value = response.data
            .filter(notification => notification !== null)
            .map(notification => ({
              ...notification,
              read: notification.status !== 0
            }))
        } else {
          ElMessage.error(response.message || '获取通知列表失败')
        }
      } catch (error) {
        ElMessage.error('获取通知列表失败')
      } finally {
        loading.value = false
      }
    }

    /**
     * 标记单个通知为已读
     * @param {number} notificationId - 通知ID
     */
    const markAsRead = async (notificationId) => {
      try {
        const response = await readNotification(notificationId)
        if (response.code === 200) {
          eventBus.emit('notification-updated')
          ElMessage.success('已确认')
          fetchNotificationList()
        } else {
          ElMessage.error(response.message || '确认失败')
        }
      } catch (error) {
        ElMessage.error('确认失败')
      }
    }

    /**
     * 标记所有通知为已读
     * 批量处理所有未读通知
     */
    const markAllAsRead = async () => {
      try {
        const unreadIds = notificationList.value
          .filter(notification => !notification.read)
          .map(notification => notification.notificationId)
        
        if (unreadIds.length === 0) {
          ElMessage.warning('没有未读通知')
          return
        }

        const promises = unreadIds.map(id => readNotification(id))
        await Promise.all(promises)
        
        notificationList.value = notificationList.value.map(notification => ({
          ...notification,
          read: true
        }))
        
        ElMessage.success('已全部标记为已读')
      } catch (error) {
        ElMessage.error('标记全部已读失败')
      }
    }

    /**
     * 确认删除通知
     * @param {number} notificationId - 要删除的通知ID
     */
    const confirmDelete = (notificationId) => {
      ElMessageBox.confirm(
        '确定要删除这条通知吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await deleteNotification(notificationId)
          if (response.code === 200) {
            notificationList.value = notificationList.value.filter(
              notification => notification.notificationId !== notificationId
            )
            eventBus.emit('notification-updated')
            ElMessage.success('删除成功')
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 用户取消删除操作
      })
    }

    // 组件挂载时获取通知列表
    onMounted(() => {
      fetchNotificationList()
    })

    return {
      loading,
      notificationList,
      formatDate,
      formatContent,
      markAsRead,
      markAllAsRead,
      confirmDelete
    }
  }
}
</script>

<style scoped>
.notification-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.notification-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.notification-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.notification-item {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.notification-item.unread {
  background-color: #ecf5ff;
}

.notification-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.notification-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-line;
}

.notification-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
  gap: 10px;
}

.action-button {
  font-size: 15px;
  padding: 8px 12px;
}

@media (max-width: 768px) {
  .notification-container {
    padding: 16px;
  }
  
  .notification-item {
    padding: 16px;
  }
}
</style> 